package net.kleinhenz.questor.ui;

import java.util.ArrayList;
import java.util.List;

import net.kleinhenz.questor.Questor;
import net.kleinhenz.questor.game.OnChoiceListener;
import net.kleinhenz.questor.model.Choice;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebStoryView extends WebView
{
	public static final String CHOICE_PROTO = "quest://";
	
	private List<OnChoiceListener> onChoiceListeners = new ArrayList<OnChoiceListener>();
	
	public WebStoryView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	public WebStoryView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	public WebStoryView(Context context)
	{
		super(context);
	}

	public void addOnChoiceListener(OnChoiceListener listener)
	{
		this.onChoiceListeners.add(listener);
		
		this.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith(CHOICE_PROTO)) {
					String choiceId = url.substring(CHOICE_PROTO.length());
					Choice choice = findChoice(choiceId);
					for (OnChoiceListener l : onChoiceListeners)
						l.onChoice(choice);
					return true;
				}
				else
					return super.shouldOverrideUrlLoading(view, url);
			}
			
			public Choice findChoice(String choiceId)
			{
				return Questor.getCurrentGame().getCurrentQuest().findChoice(choiceId);
			}
		});
	}

	public void removeOnChoiceListener(OnChoiceListener listener)
	{
		this.onChoiceListeners.remove(listener);		
	}
	
	@Override
	public void loadData(String data, String mimeType, String encoding)
	{
		StringBuffer buf = new StringBuffer();
		buf.append("<xhtml><head><style>");
		buf.append("body{font-family:serif;font-size:16px}");
		buf.append("</style></head><body>");
		buf.append(data);
		buf.append("</body></xhtml>");

		super.loadData(buf.toString(), mimeType, encoding);
	}
}
